<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: 'home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button
            type="primary"
            round
            @click="changeDialogVisible"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表主体区域 -->
      <el-table
        :data="users"
        :stripe="true"
        :border="true"
      >
        <el-table-column
          type="index"
          width="180"
        > </el-table-column>
        <!-- <el-table-column prop="id" label="ID" width="180"> </el-table-column> -->
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
        > </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
        > </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
        > </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
        >
          <!-- 加工布尔值数据，所以用作用域插槽 -->
          <template slot-scope="s">
            <el-switch
              active-color="#409eff"
              v-model="s.row.mg_state"
              inactive-color="#ccc"
              @change="changeUserState(s.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="s">
            <!-- 编辑 -->
            <el-button
              type="primary"
              @click="openEdit(s.row.id)"
              size="mini"
            >
              <i class="el-icon-edit"></i>
            </el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              @click="deleteUser(s.row.id)"
              size="mini"
            >
              <i class="el-icon-delete"></i>
            </el-button>

            <!-- 修改/分配权限 由于图标不能让用户知道含义，所以需要有文字提示 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                @click="openAllot(s.row)"
                size="mini"
              >
                <i class="el-icon-s-tools"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="resetAddForm"
    >
      <!-- 弹出框主体 -->

      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="addForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="addForm.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input
            v-model="addForm.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input
            v-model="addForm.mobile"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ensureAdd"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed='resetEditForm'
    >
      <!-- 弹出框主体 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <!-- 不需要验证的话就不需要prop属性 -->
        <el-form-item label="用户名">
          <el-input
            v-model="editForm.username"
            disabled
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机"
          prop="mobile"
        >
          <el-input
            v-model="editForm.mobile"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input
            v-model="editForm.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ensureEdit"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allotDialogVisible"
      width="50%"
    >
      <!-- 弹出框主体 -->
      <p>当前的用户：{{userInfo.username}}</p>
      <p>当前的角色：{{userInfo.role_name}}</p>
      <div>分配新角色：<el-select
          v-model="selectedRoleID"
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <!-- <el-select></el-select> -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ensureAllot"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 自定义验证规则 最后一个callback必须记得加()
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (regEmail.test(value)) {
          // console.log(1)
          return callback()
        }
        // 验证不通过
        // console.log(2)
        // 下面这种写法不通过
        // return new Error('请输入合法的邮箱！')
        // 合法写法
        callback(new Error('请输入合法的邮箱！'))
      }, 500)
    }
    // data数据
    return {
      // 发送请求 用户数据列表
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      // 一共多少条数据
      total: 0,
      // 用户数据列表
      users: [],
      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 4,
      addDialogVisible: false,
      editDialogVisible: false,
      allotDialogVisible: false,
      // 分配用户权限弹框 当前所要更改的
      userInfo: {
        id: 0,
        username: '',
        role_name: '',
      },
      rolesList: [],
      // 已经选中的角色ID值
      selectedRoleID: '',
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editForm: {
        id: 0,
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 自定义验证规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 自定义验证规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            min: 3,
            max: 13,
            message: '长度在 3 到 13 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    // 请求数据
    async getUsers() {
      var { data: result } = await this.$axios.get('users', {
        // 必须写params，否则拿不到
        params: this.queryInfo,
      })
      // console.log(result, 'res')
      // console.log(result.data, 'data')
      if (result.meta.status != 200) {
        return this.$message.error('请求用户数据列表失败！')
      }
      // 请求成功
      this.total = result.data.total
      this.users = result.data.users
      // console.log(this.total, 'total')
      // console.log(this.users, 'users')
    },
    // 操作里面的编辑用户列表 弹出对话框
    async openEdit(id) {
      this.editDialogVisible = true
      // 根据id获取数据
      var { data: result } = await this.$axios.get(`users/${id}`)
      // console.log(result)
      if (result.meta.status == 200) {
        this.editForm = result.data
      } else {
        this.$message.error(result.meta.msg)
      }
    },
    // 打开分配权限对话框
    async openAllot(userInfo) {
      this.userInfo.id = userInfo.id
      this.userInfo.username = userInfo.username
      this.userInfo.role_name = userInfo.role_name
      // 拿到所有的角色
      var { data: result } = await this.$axios.get('roles')
      // console.log(result);
      if (result.meta.status == 200) {
        this.rolesList = result.data
      } else {
        this.$message.error(result.meta.msg)
      }

      this.allotDialogVisible = true
    },
    // 确认修改分配的权限
    async ensureAllot() {
      // console.log(1);
      if (this.selectedRoleID) {
        // console.log(this.userInfo.id)
        var { data: result } = await this.$axios.put(
          `users/${this.userInfo.id}/role`,
          {
            rid: this.selectedRoleID,
          }
        )
        // console.log(result)
        if (result.meta.status != 200) {
          // 设置角色失败
          return this.$message.error(result.meta.msg)
        }
        // 设置角色成功
        this.$message.success(result.meta.msg)
        // 重置选择的角色
        this.selectedRoleID = ''
        this.getUsers()
        this.allotDialogVisible = false
      } else {
        // 用户没有选择角色
        this.$message.error('请选择角色！')
      }
    },
    // 操作页面的删除按钮 弹出对话框 根据用户id
    async deleteUser(id) {
      // console.log(1)
      var result = await this.$confirm(
        '此操作将会永久删除该用户，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((e) => {
        return e
      })
      // console.log(result)
      if (result === 'confirm') {
        // 确定删除
        var { data: result2 } = await this.$axios.delete(`users/${id}`)
        // console.log(result2);
        if (result2.meta.status == 200) {
          // 删除成功
          this.$message.success(result2.meta.msg)
          this.getUsers()
        } else {
          // 删除失败
          this.$message.error(result2.meta.msg)
        }
      }
    },
    // 打开确认删除对话框
    // openDelete() {},
    // 每一页展示多少条
    handleSizeChange(s) {
      // console.log(`每页 ${s} 条`)
      this.queryInfo.pagesize = s
      this.getUsers()
    },
    // 跳转到第多少页
    handleCurrentChange(p) {
      console.log(`当前页: ${p}`)
      this.queryInfo.pagenum = p
      this.getUsers()
    },
    // 改变用户状态 保证用户修改后和服务器里数据一致
    async changeUserState(userInfo) {
      // console.log(userInfo)
      var { data: result } = await this.$axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      console.log(result)
      if (result.meta.status != 200) {
        // 修改回修改前状态
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(result.meta.msg)
      }
      // 请求成功
      // console.log(1);
      this.$message.success(result.meta.msg)
    },
    // 添加用户按钮 打开对话框
    changeDialogVisible() {
      this.addDialogVisible = true
    },
    // 重置对话框表单
    resetAddForm() {
      // console.log(this.$refs);
      this.$refs.addFormRef.resetFields()
      // console.log(1)
    },
    // 确认添加用户 并且关闭对话框
    ensureAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return this.$message.error('验证不通过')
        // 验证通过
        var { data: result } = await this.$axios.post('users', this.addForm)
        // console.log(result)
        // 添加成功
        if (result.meta.status == 201) {
          this.$message.success(result.meta.msg)
          this.getUsers()
          this.addDialogVisible = false
        } else {
          // 添加失败
          this.$message.error(result.meta.msg)
        }
      })
    },
    // 确认修改 关闭对话框
    ensureEdit() {
      // 这里需要调用form的引用
      this.$refs.editFormRef.validate(async (valid) => {
        // 布尔值
        console.log(valid)
        if (!valid) return this.$message.error('不合法的值')
        // 验证通过 发送请求
        var { data: result } = await this.$axios.put(
          `users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        console.log(result)
        if (result.meta.status == 200) {
          this.editDialogVisible = false
          this.$message.success(result.meta.msg)
          this.getUsers()
        } else {
          this.$message.error(result.meta.msg)
        }
      })
    },
    // 重置修改用户对话框验证提示信息
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
  },

  // 生命周期
  created() {
    // 发送请求
    this.getUsers()
  },
}
</script>
<style lang="less" scoped>
.el-card {
  .el-row {
    height: 50px;
    .el-col {
      > div {
        height: 40px;
      }
    }
  }
}
</style>
